using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Services;
using System.Xml;
using Dimok;
using Dimok.BlackBook;
using Dimok.Data;
using Dimok.Data.Database;
using Dimok.Exceptions;
using Data;

namespace Dimok.Aspx.Manager.Lib
{
	/// <summary>
	/// Summary description for BlackBook_WC_aloaners.
	/// </summary>
	public class BlackBook_WC_AutoBank : BlackBook_WS
	{
		#region CODEGEN *************************
		public BlackBook_WC_AutoBank():base()
		{
			//CODEGEN: This call is required by the ASP.NET Web Services Designer
			InitializeComponent();
		}
		#endregion
		#region Component Designer generated code
		
		//Required by the Web Services Designer 
		private IContainer components = null;
				
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if(disposing && components != null)
			{
				components.Dispose();
			}
			base.Dispose(disposing);		
		}
		
		#endregion
		private const string TABLE_BOOK_VALUE = "BookValue";
		#region Fetch ************************
		private Manheim.ManheimServer MMR{
			get{
				//if( this.Context.Cache["MMR"] != null )return (Manheim.ManheimServer)this.Context.Cache["MMR"];
				//HttpContext.Current.Cache["MMR"] = 
				return Manheim.ManheimClient.Activate();
				//return MMR;
			}
		}
		[WebMethod]
		public string[] FetchYears(){
			return SQL.ExecuteScalarArray(UOX.dbRaw,"SELECT DISTINCT Year FROM t_Car_YearMake ORDER BY Year DESC");
		}
		[WebMethod]
		public string[] FetchMakes(int year){
			return SQL.ExecuteScalarArray(UOX.dbRaw,"SELECT DISTINCT Make FROM t_Car_YearMake WHERE Year=@Year ORDER By Make",year);
		}
		
		private string FetchVIN(string vin,string state,int mileage){
			try{
				if( vin.Length != 17 && vin.Length != 9 )throw new Exception("VIN must have 17,10 or 9 positions.");
				string vinFetch = vin.Length == 10 ? vin.Substring(0,8)+vin.Substring(9,1) : vin;
				PriceInfoDS dsPI = BlackBook.BlackBook.LoadPriceInfo(vinFetch,state,mileage);
				if( dsPI.CarInfo.Count == 0 )throw new Exception("No car found for this VIN.");
				if( dsPI.CarInfo.Count > 1 )return SQL.XmlInnerText(dsPI);
				PriceInfoDS.CarInfoRow drCI = dsPI.CarInfo[0];
				drCI.VIN = vin;
				try{
					var dsMMR = MMR.GetPriceByVIN("SE",vin,mileage,drCI.Make+" "+drCI.Model+" "+drCI.Series+" "+drCI.Body_Style);
					dsPI.BookValue.AddBookValueRow(dsMMR.Price.FindByType(Manheim.PriceType.Average+"").Price, Manheim.PriceType.Average+"", "M", "", 0,0);
				}catch(Exception exc){ClientException.Publish(exc,true);}
				new UOX().BB.SaveCarInfo(dsPI);
				return GetCarInfo(vin);
			}catch(Exception exc){ throw new ClientException(exc); }
		}
		
		public string FetchPriceInfo(string vin,string year,string make,string model,string series,string bodyStyle,string[] addOns,string state,int mileage){
			if( vin.Length != 17 )vin = "";
			try{
				PriceInfoDS dsPI = BlackBook.BlackBook.LoadPriceInfo(year,make,model,series,bodyStyle,addOns,state,mileage);
				if( dsPI.CarInfo[0].VIN != "" ){
					try{
						var dsMMR = MMR.GetPriceByVIN("SE",dsPI.CarInfo[0].VIN,mileage,make+" "+model+" "+series+" "+bodyStyle);
						dsPI.BookValue.AddBookValueRow(dsMMR.Price.FindByType(Manheim.PriceType.Average+"").Price, Manheim.PriceType.Average+"", "M", "", 0,0);
					}catch(Exception exc){ClientException.Publish(exc,true);}
				}
				if( vin != "" )dsPI.CarInfo[0].VIN = vin;
				if( dsPI.CarInfo[0].VIN == "" )dsPI.CarInfo[0].VIN = MakeVin(year,make,model,series,bodyStyle);
				if( dsPI.CarInfo.Count > 0 ){
					new UOX().BB.SaveCarInfo(dsPI);
					return GetCarInfo(dsPI.CarInfo[0].VIN);
				}
				return SQL.XmlInnerText(dsPI);
			}catch(Exception exc){ throw new ClientException(exc); }
		}
		private string MakeVin(string year,params string[] parts){
			string s = year.Substring(2,2);
			foreach( string part in parts )
				s += MakeVinPosition(part+"");
			return s;
		}
		private string MakeVinPosition(string part){
			string digits = Regex.Match(part,"\\d+").Value;
			return (part+"") == "" ? "" : part.Substring(0,1) + (digits==""?part.Replace(" ","").Length.ToString("X"):digits);
		}
		[WebMethod]
		public string GetCarInfo(string vin){
			try{
				return new UOX().BB.PriceInfoXml(vin);
			}catch(Exception exp){throw new ClientException(exp);}
		}
		[WebMethod]
		public string GetApplCarInfo(){
			try{
				UOX uox = new UOX();
				PriceInfoDS dsPriceInfo = new PriceInfoDS();
				if( !uox.hasApplID )return dsPriceInfo.GetXml();
				SQLHelperEx.ExecuteDatasetEx(uox.db,dsPriceInfo.CarInfo,uox.CarInfo.SQL_V);
				if( dsPriceInfo.CarInfo.Count == 0 )throw new ASPException("No car info found for applicant "+uox.applID+".");
				SQLHelperEx.ExecuteDatasetEx(uox.db,dsPriceInfo.AddOns,"SELECT * FROM v_Car_AddOn WHERE "+uox.ApplicantFilter());
				return SQL.XmlInnerText(dsPriceInfo);
			}catch(Exception exp){throw new ClientException(exp);}
		}
		#endregion Fetch ************************
		#region Applicant Car Info ****************************************
		[WebMethod]
		public void SetApplCarField(string fieldName,string fieldValue){
			try{
				UOX uox = new UOX();
				if( !uox.hasApplID )return;
				uox.CarInfo.Update(fieldName,fieldValue);
			}catch(Exception exc){ throw new ClientException(exc); }
		}
			#region Get **********************
		[WebMethod]
		public object GetApplCarField(string fieldName){
			try{
				UOX uox = new UOX();
				object v = uox.CarInfo.Get(fieldName);
				if( System.DBNull.Value.Equals(v) )v = new object();
				return v;
			}catch(Exception exc){ throw new ClientException(exc); }
		}
			#endregion Get *********************
		#endregion Applicant Car Info
	}
}
